package com.olt.server.role;


import com.olt.dao.user.IRoleDao;
import com.olt.dao.user.IRolePower;
import com.olt.domain.user.OltRole;
import com.olt.domain.user.RolePower;
import com.olt.result.PageResult;
import com.olt.server.dto.PageInput;
import com.olt.server.role.dto.CreateRoleInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackForClassName="RuntimeException")
public class RoleServer {
    @Autowired
    IRolePower iRolePower;
    @Autowired
    IRoleDao iRoleDao;

    public void createRole(CreateRoleInput input){
        OltRole oltRole=new OltRole();
        oltRole.setRoleName(input.roleNameEn);
        oltRole.setRoleNameZh(input.roleName);
        if(input.id!=null){
            iRolePower.deleteByRoleId(input.id);
            iRoleDao.updateRole(input.roleNameEn,input.roleName, input.id);
            oltRole.setRoleId(input.id);

        }
        else {
            oltRole = iRoleDao.save(oltRole);
        }

        for(Long id: input.ids){
            iRolePower.save(new RolePower(oltRole.getRoleId(),id));
        }
    }

    public OltRole getOltRoleByName(String name){
        return iRoleDao.getFirstByRoleName(name);
    }


    public Page<OltRole> getOltRole(PageInput input){
        Pageable page= PageRequest.of(input.getCurrentPage(), input.getSize());
        return iRoleDao.findAllByRoleNameContainingOrRoleNameZhContaining(input.key,input.key,page);
    }

    public void deleteRole(Long[] Ids) {
        for (Long id : Ids) {
            iRoleDao.deleteById(id);
        }
    }

    public CreateRoleInput getRoleForEdit(Long id){
        OltRole role =iRoleDao.getOne(id);
        CreateRoleInput input =new CreateRoleInput();
        input.setRoleName(role.getRoleNameZh());
        input.setRoleNameEn(role.getRoleName());
        input.setNames(iRolePower.findIdByRoleId(id));
        return input;
    }

}
